//
//  CXHTradPlusNativeExpressAdapter.m
//  CXHAdSDK-TradPlus
//
//  Created by 陈坤 on 2023/9/23.
//

#import "CXHTradPlusNativeExpressAdapter.h"

#import <TradPlusAds/TradPlusAdWaterfallItem.h>
#import <CXHAdSDK-Core/CXHAdSDK.h>
#import <CXHAdSDK-Core/CXHAdSDKNativeExpressAd.h>
#import <CXHAdSDK-Kit/CXHUtilsKit.h>
#import <CXHAdSDK-Adapter/CXHAdSDKAdapter.h>
#import <CXHAdSDK-Adapter/CXHAdapterNativeExpressAdapter.h>
//#import <CXHAdSDK-Adapter/CXHAdapterNativeAdData.h>

@interface CXHTradPlusNativeExpressAdapter ()<CXHAdSDKNativeExpressAdDelegate>{
    NSHashTable<UIView<CXHAdapterNativeExpressAdViewDelegate> *> *_weakHashTable;
}

@property (nonatomic, strong)CXHAdSDKNativeExpressAd *nativeAd;

@property (nonatomic, assign) BOOL isInit;

@property (nonatomic, assign) BOOL isC2SBidding;

@end

@implementation CXHTradPlusNativeExpressAdapter

//根据event实现相关流程
- (BOOL)extraActWithEvent:(NSString *)event info:(NSDictionary *)config
{
    if([event isEqualToString:@"C2SBidding"]){
        //从三方SDK获取价格
        [self getECPMC2SBidding];
    } else if([event isEqualToString:@"LoadAdC2SBidding"]) {
        //竞价成功后的加载流程
        [self loadAdC2SBidding];
//        [self.nativeAd sendWinNotice:self.nativeAd.getBidPrice];
    } else if ([event isEqualToString:@"C2SLoss"]) {
        NSString *topPirce = config[@"topPirce_cny"];
        [self.nativeAd sendLossNotice:[topPirce integerValue]];
    } else {
        return NO;
    }
    return YES;
}

- (void)loadAdC2SBidding {
    if ([self isReady]) {
        [self.nativeAd sendWinNotice:self.nativeAd.getBidPrice];
        [self AdLoadFinsh];
    }else{
        NSError *loadError = [NSError errorWithDomain:@"Load nativeExpress failed" code:-4 userInfo:@{NSLocalizedDescriptionKey : @"C2S nativeExpress not ready"}];
        [self AdLoadFailWithError:loadError];
    }
}

- (void)getECPMC2SBidding {
//    [self initSDK:self.waterfallItem.config];
    [self startC2SBidding];
}

//通过三方API获取ECPM
- (void)startC2SBidding {
    self.isC2SBidding = YES;
    NSString *posid = self.waterfallItem.config[@"posid"];
    
    if (kCXHStringIsEmpty(posid)) {
        NSDictionary *dic = @{@"error": @"get bid price failed"};
        [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFail" info:dic];
        return;
    }
    
    self.nativeAd.posId = posid;
    
    [self loadAdWithWaterfallItem:self.waterfallItem];
}

- (CXHAdSDKNativeExpressAd *)nativeAd{
    if (_nativeAd == nil) {
        _nativeAd = [[CXHAdSDKNativeExpressAd alloc] initWithAdSize:self.waterfallItem.templateRenderSize];;
        _nativeAd.delegate = self;
    }
    return _nativeAd;
}

//初始化自定义平台，设置平台参数（海外平台的隐私设置）加载广告
- (void)loadAdWithWaterfallItem:(TradPlusAdWaterfallItem *)item
{
    [self initSDK:item.config];
    //通过 item.config 获取后台配置信息
    NSString *posid = item.config[@"posid"];
    
    if (kCXHStringIsEmpty(posid)) {
        [self  AdConfigError];
        return;
    }
    
    self.nativeAd.posId = posid;
    if (item.nativeRootViewController) {
        self.nativeAd.controller = item.nativeRootViewController;
    }
    NSDictionary *localParams = [item.extraInfoDictionary CXH_objectOrNilForKey:@"localParams"];
    if (localParams) {
        id isClose = [localParams CXH_objectOrNilForKey:@"showclose"];
        if (isClose != nil && [isClose isEqualToString:@"true"]) {
            self.nativeAd.hiddenCloseView = YES;
        }
        
        id isLeft = [localParams CXH_objectOrNilForKey:@"lefttype"];
        if (isLeft != nil && [isLeft isEqualToString:@"true"]) {
            self.nativeAd.expressType = CXHAdSDKNativeExpressTypeLeft;
        } else {
            self.nativeAd.expressType = CXHAdSDKNativeExpressTypeImage;
        }
    }
    
    [self.nativeAd load:1];
}

- (void)initSDK:(NSDictionary *)config {
    if (self.isInit) {
        return;
    }
    self.isInit = YES;
    NSString *domain = [config CXH_objectOrNilForKey:@"domain"];
    if (kCXHStringIsEmpty(domain)) {
        domain = @"";
    }
    
    NSString *appid = [config CXH_objectOrNilForKey:@"appid"];
    if (!kCXHStringIsEmpty(appid)) {
        [CXHAdSDK initWithAppId:appid requestDomain:domain completionBlock:^(NSError * _Nullable error) {
            if (error) {
                [self AdConfigError];
            }
        }];
    }
}

//此方法用于返回是否过期状态
- (BOOL)isReady
{
    return (self.nativeAd != 0);
}

- (void)templateRender:(UIView *)subView{
    UIView<CXHAdapterNativeExpressAdViewDelegate> *adview = [_weakHashTable.allObjects firstObject];
    if (adview == nil) {
        return;
    }
    [adview render];
}


#pragma mark - CXHAdSDKNativeExpressAdDelegate
/**
 信息流广告请求成功

 @param nativeAd 广告实例
 @param adViewArray 广告模板集合
 */
- (void)CXH_nativeAdSucessToLoad:(CXHAdSDKNativeExpressAd *)nativeAd
                     adViewArray:(NSArray<__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *> *)adViewArray{
    UIView<CXHAdapterNativeExpressAdViewDelegate> *adView = [adViewArray firstObject];
    [_weakHashTable addObject:adView];
    TradPlusAdRes *res = [[TradPlusAdRes alloc] init];
    res.adView = adView;
    //模版类型只需要绑定 res.adView
    //完成绑定，设置Res。用于TP SDK的原生界面渲染
    self.waterfallItem.adRes = res;
    if (self.isC2SBidding) {
        NSInteger price = self.nativeAd.getBidPrice;
        if (price <= 0) {
            NSDictionary *dic = @{@"error": @"get bid price failed"};
            [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFail" info:dic];
            return;
        }
        //通过接口向TradPlusSDK回传ecpm和三方版本号
        float f = price/100.00;
        NSString *ecpmStr = [NSString stringWithFormat:@"%.2f", f];
        NSDictionary *dic = @{@"ecpm":ecpmStr,@"version":[CXHAdSDK getSDKVersion]};
        [self ADLoadExtraCallbackWithEvent:@"C2SBiddingFinish" info:dic];
    } else {
        [self AdLoadFinsh];
    }
    
    
}

/**
 信息流广告请求失败

 @param nativeAd 广告实例
 @param error 请求错误描述
 */
- (void)CXH_nativeAdFailToLoad:(CXHAdSDKNativeExpressAd *)nativeAd
                         error:(NSError *)error{
    [self AdLoadFailWithError:error];
}

/**
 信息流广告渲染成功

 @param adView 广告视图
 */
- (void)CXH_nativeAdViewRenderOrRegistSuccess:(UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    [self didAddSubView];
}

/**
 信息流广告渲染失败

 @param adView 广告视图
 */
- (void)CXH_nativeAdViewRenderOrRegistFail:(UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    NSError *error = CXHAdapterErrorDefaultDomain(-1, @"ad is render failed");
    [self AdShowFailWithError:error];
}

/**
 信息流广告被点击

 @param nativeAd 广告模板
 */
- (void)CXH_nativeAdClicked:(CXHAdSDKNativeExpressAd *)nativeAd
                     adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView loadingPageURL:(NSString *)loadingPageURL{
    [self AdClick];
}

/**
 信息流广告被关闭
 
 @param nativeAd 广告模板
 */
- (void)CXH_nativeAdClose:(CXHAdSDKNativeExpressAd *)nativeAd
                   adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    [self AdClose];
}

/**
 信息流广告被展示
 
 @param nativeAd 广告实例
 */
- (void)CXH_nativeAdExposure:(CXHAdSDKNativeExpressAd *)nativeAd
                      adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    [self AdShow];
}

/**
 信息流广告落地页被关闭
 
 @param nativeAd 广告实例
 */
- (void)CXH_nativeAdCloseLandingPage:(CXHAdSDKNativeExpressAd *)nativeAd
                              adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    
}


@end
